﻿using System;
using System.Xml;

namespace XmlReadWriteSample
{
    class Program
    {
        static void Main(string[] args)
        {
        //  ReadXmlDoc1("customer1.xml");
       //   ReadXmlDoc2("customer2.xml");
      WriteXmlDoc("cw3.xml");

        }
        private static void WriteXmlDoc(string fileName)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            using (XmlWriter writer = XmlWriter.Create(@"..\..\..\" + fileName, settings))
            {
                writer.WriteStartElement("customer");
                //写属性
                writer.WriteAttributeString("id", "1");
                writer.WriteAttributeString("status", "archived");
                writer.WriteElementString("firstname", "Jim");
                writer.WriteElementString("lastname", " Bo");
                writer.WriteStartElement("birthdate");
                writer.WriteValue(DateTime.Now);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
            Console.WriteLine("写入成功");

        }

        private static void ReadXmlDoc1(string fileName)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreWhitespace = true;
            using (XmlReader reader = XmlReader.Create(fileName, settings))
                while (reader.Read())
                {
                    Console.Write(new string(' ', reader.Depth * 2)); // Write indentation
                    Console.WriteLine(reader.NodeType);
                }
        }
        private static void ReadXmlDoc2(string fileName)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreWhitespace = true;
            settings.DtdProcessing = DtdProcessing.Parse; // Required to read DTDs
            using (XmlReader r = XmlReader.Create(fileName, settings))
                while (r.Read())
                {
                    Console.Write(r.NodeType.ToString().PadRight(17, '-'));
                    Console.Write("> ".PadRight(r.Depth * 3));
                    switch (r.NodeType)
                    {
                        case XmlNodeType.Element:
                        case XmlNodeType.EndElement:
                            Console.WriteLine(r.Name); break;
                        case XmlNodeType.Text:
                        case XmlNodeType.CDATA:
                        case XmlNodeType.Comment:
                        case XmlNodeType.XmlDeclaration:
                            Console.WriteLine(r.Value); break;
                        case XmlNodeType.DocumentType:
                            Console.WriteLine(r.Name + " - " + r.Value); break;
                        default: break;
                    }
                }
        }
    }
}
